import { defineStore } from "pinia";
import userApi from "@/api/userInfo";
import type { LoginParamsData, UserInfoData } from "@/api/userInfo";
import { staticRoutes,allAsyncRoutes,anyRoute } from "@/router/routes";
import  type { RouteRecordRaw} from "vue-router"
import router from "@/router";
import {cloneDeep} from 'lodash'
interface UserInfoStoreStateData {
  token: string | null;
  userInfo: UserInfoData;
  menuRoutes:RouteRecordRaw[]
}

//从所有的路由中过滤出属于自己的路由
function filterAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],routeNames:string[]){
  let res =allAsyncRoutes.filter(item=>{
    if(routeNames.indexOf(item.name as string)!==-1){
      if(item.children && item.children.length){
        item.children=filterAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })
  return res
}

//封装把多个路由进行动态添加
function addRoutes(routes:RouteRecordRaw[]){
  routes.forEach(item=>{
    router.addRoute(item)
  })
}


// 封装用户退出后重置路由信息
function resetRouter(){
  let routes=router.getRoutes()
  routes.forEach(item=>{
    router.removeRoute( item.name as string)
  })

  addRoutes(staticRoutes)
}
export const useUserInfoStore = defineStore("userInfo", {
  state(): UserInfoStoreStateData {
    return {
      token: localStorage.getItem("token_key") || "",
      userInfo: {
        "routes": [],
        "buttons": [],
        "roles": [],
        "name": '',
        "avatar": ''
      },
      menuRoutes:staticRoutes
    }
  },
  actions:{
    async login(LoginParams:LoginParamsData){
        try {
            const result=await userApi.userLogin(LoginParams)
            this.token=result.token
            localStorage.setItem('token_key',result.token)
            return "ok"
        } catch (error) {
            return Promise.reject(error)
        }
    },
    async getUserInfo(){
        try{
            const result=await userApi.getUserInfo()
            this.userInfo=result
            let userAsyncRoutes=filterAsyncRoutes(cloneDeep(allAsyncRoutes),result.routes)
            addRoutes(userAsyncRoutes.concat(anyRoute))
            this.menuRoutes=staticRoutes.concat(userAsyncRoutes,anyRoute)
            return 'ok'
        }catch(error){
            return Promise.reject(error)
        }
    },
    async reset(){
        this.token=''
        Object.assign(this.userInfo,{
            "routes": [],
            "buttons": [],
            "roles": [],
            "name": '',
            "avatar": ''
        })
        localStorage.removeItem('token_key')
    },
    async logout(){
        try {
            await userApi.userLogout()
            this.reset()
            resetRouter()
            return 'ok'
        } catch (error) {
            return Promise.reject(error)
        }
    }
  },
  getters:{
    
  }
})
